<!DOCTYPE html>
<html>
<head>
    <title>上传会员头像照片</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body style="background-color: rgb(254, 254, 255);">
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>上传会员头像照片</h2>    
    <div class="form-row">
        <h4 style="width:70px;">会员姓名</h4>
        <input id="cusNameInput" style="width:100px;" oninput="handleInput();">
    </div>
    <div id="cusNameList"></div>
    <hr style="border-top:1px dashed;">
    <div id="compPicBox">
        <h3>上传头像（建议比例3:4）</h3>
        <input type="file" name='image' id="fileInput" accept="image/*" style="display: none;">
        <div id="uploadMsg" ></div>
        <div id="uploadStatus"></div>
        <button id='browseButton' onclick="openFileBrowser();" style="margin-top:20px;">浏览</button>
        <button id="upload" onclick="uploadFile();">上传</button>
    </div>



    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let insName;
        let insId;
        let insRole;
        let insList;
        let cus_list;
        let selectedFile;
        
        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();        
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不允许进入该页面，返回Index
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log('cus list:',data);
                cus_list=data;
                  })
                .catch(error => console.error('Error:', error)); 
                
                document.getElementById('browseButton').disabled=true;
                document.getElementById('upload').disabled=true;

                document.getElementById('fileInput').addEventListener('change', handleFileSelection);
                const fileInput = document.getElementById("fileInput");
                fileInput.addEventListener("change", handleFileSelection);
         
        });

        
        function handleInput() {
            // 获取输入框中的值
            const cusNameInput=document.getElementById('cusNameInput');
            const searchTerm = document.getElementById("cusNameInput").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusNameList");
            document.getElementById('browseButton').disabled=true;
            document.getElementById('upload').disabled=true;


            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";
                resultList.classList.add('cus-list-cls-input');
                resultList.style.left='213px';
                resultList.style.top='129px';
                resultList.style.paddingLeft='10px';
                resultList.style.paddingRight='15px';
                resultList.style.lineHeight='32px';

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;
                    // 添加点击事件监听器,点击名字时执行。
                    listItem.addEventListener("click", function() {                        
                        cusNameInput.value = name;
                        document.getElementById('browseButton').disabled=false;
                        document.getElementById('upload').disabled=false;
                        // 点击后隐藏名字列表框
                        resultList.style.display = "none";

                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                }
            });        
        }

        function openFileBrowser() {
            document.getElementById('fileInput').click();
        }

        function newSelectedName(name){
            const cusName=document.getElementById('cusNameInput').value;
            const fileExtension = name.split('.').pop();
            const filename = cusName + '.' + fileExtension;
            return filename
        }

        function handleFileSelection(event) {
            selectedFile = event.target.files[0];
            // console.log(selectedFile.name)
            const uploadMsg=document.getElementById('uploadMsg');
            const newFileName=newSelectedName(selectedFile.name);
            uploadMsg.textContent=`已选择文件：${newFileName}`
           
        }

        function uploadFile() {
            if (!selectedFile) {
                alert("请选择要上传的图片");
                return;
            }

            const uploadStatus=document.getElementById('uploadStatus');
            uploadStatus.innerHTML='正在上传';
            const newFileName=newSelectedName(selectedFile.name);
            
            const url = "/deal_upload_cus_photo?filename=" + encodeURIComponent(newFileName);

            let formData = new FormData();
            formData.append("file", selectedFile); 
            formData.append("filename", newFileName);
            // console.log(url)

            let xhr = new XMLHttpRequest();
            xhr.open("POST", url);
            xhr.onload = function() {
                console.log('xhr status:',xhr.status)     
                if (xhr.status === 200) {
                    document.getElementById('uploadMsg').textContent=`${newFileName} 上传成功`;
                    alert("上传成功");
                } else {
                    const errorResponse = JSON.parse(xhr.responseText);
                    const errorMessage = errorResponse.message;
                    // console.log('message:',errorMessage)
                    document.getElementById('uploadMsg').textContent='上传失败，请联系管理员。'
                    alert("上传失败，请联系管理员。错误："+errorMessage);
                }
            };
            xhr.send(formData);
            uploadStatus.innerHTML='';
        }
   
    </script>
  
</body>
</html>
